#pragma once

#include <iostream>
#include <cstdlib>
#include <cstdarg>
#include <cstdio>
#include <string>
#include <ctime>
#include <unistd.h>


enum
{
    Info = 1,
    Warning,
    Error,
    Unknown,
    Debug,
    Fatal
};

static std::string filename = "./log/Message.log";

static std::string to_level_str(int level)
{
    switch (level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Unknown:
        return "Unknown";
    }
}

static std::string get_cur_time()
{
    time_t curr = time(nullptr);
    struct tm *tmp = localtime(&curr);

    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%d-%d-%d %d:%d:%d", tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec);

    return buffer;
}

void logMessage(int level, const char *format, ...)
{
    char logLeft[1024];
    std::string level_str = to_level_str(level);
    std::string cur_time = get_cur_time();

    snprintf(logLeft, sizeof(logLeft), "[%s][%s][%d]", level_str.c_str(), cur_time.c_str(), getpid());

    char logRight[1024];
    va_list p;
    va_start(p, format);
    vsnprintf(logRight, sizeof(logRight), format, p);
    va_end(p);

    // 将日志信息写入文件中
    FILE *fp = fopen(filename.c_str(), "a");
    if (fp == nullptr)
        return;

    fprintf(fp, "%s%s\n", logLeft, logRight);

    fflush(fp); // close也会刷

    fclose(fp);
}
